package com.tencent.wxcloudrun.util;

import com.tencent.wxcloudrun.constant.WxChatConstant;
import com.tencent.wxcloudrun.model.WeChatTemplateMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class WxSendMessageUtils {

    // restTemplate的请求方式
    @Autowired
    protected RestTemplate restTemplate;

    // 获取Access_Token工具类
    @Autowired
    protected WeChetAccessToken weChetAccessToken;

    /**
     * 发送方法
     */
    public String send(String openId, String templateId, Map<String, WeChatTemplateMsg> data) {
        System.out.println("getToken");
        String accessToken = weChetAccessToken.getToken();
        System.out.println("token：" + accessToken);

        String url = WxChatConstant.Url.MESSAGE_SEND_URL.replace("ACCESS_TOKEN", accessToken);
        System.out.println("调用的接口地址为:" + url);

        // 拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        // openId
        sendBody.put("touser", openId);
        // 模板Id
        sendBody.put("template_id", templateId);
        // 模板顶色
        sendBody.put("topcolor", "#FF0000");
        // 模板参数
        sendBody.put("data", data);
        // 跳转url
        sendBody.put("url", "");

        System.out.println("postForEntity:" + sendBody.toString());
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
        System.out.println("响应：" + forEntity.getBody());
        return forEntity.getBody();
    }

}